import socket
import logging
import asyncio
from typing import Optional

async def send_xml_request(xml_data: str) -> str:
    """
    发送XML请求到卡系统服务器
    """
    try:
        # 创建TCP socket
        reader, writer = await asyncio.open_connection('192.168.6.224', 7910)
        
        # 计算XML长度并添加4位前缀
        xml_bytes = xml_data.encode('gbk')
        length_prefix = str(len(xml_bytes)).zfill(4)
        full_request = length_prefix.encode('gbk') + xml_bytes
        
        logging.info(f"发送请求: {full_request}")
        
        # 发送数据
        writer.write(full_request)
        await writer.drain()
        
        # 读取4字节长度前缀
        length_data = await reader.read(4)
        response_length = int(length_data.decode('gbk'))
        
        # 读取响应数据
        response_data = await reader.read(response_length)
        response_text = response_data.decode('gbk')
        
        logging.info(f"收到响应: {response_text}")
        
        # 关闭连接
        writer.close()
        await writer.wait_closed()
        
        return response_text
    except Exception as e:
        logging.error(f"TCP通信错误: {str(e)}")
        raise Exception(f"TCP通信错误: {str(e)}") 